#include <mips/regdef.h>

	.text
	.align	2
	.globl	heapSort
	.ent	heapSort

heapSort:
# Creacion del stack frame
	.frame		$fp, 40, ra
	.set		noreorder
	.cpload		t9
	.set		reorder
	subu		sp, sp, 40
	.cprestore	24

	sw		ra,  32(sp)
	sw		$fp, 28(sp)

	move	$fp, sp

# Guarda el parametro en el stack
	sw	a0, 40($fp)		# words
	sw	a1, 44($fp)		# arraySize

	sw	zero, 20($fp)	# i = 0
	
	lw	a1, 44($fp)		# arraySize
	sw	a1, 16($fp)		# heapSize = arraySize

	#i = arraySize/2
	
	lw		t0, 20($fp)	#i	
	lw		a1, 44($fp)	#arraysize
	addu	t2, zero, 2	
	
	div		a1, t2		#arraySize/2	
	mflo	v0
	
	sw		v0, 20($fp)	# i = arraySize/2
	
	#for (i = arraySize/2; i >= 0; i--)
for_i_uno:
	lw		t0, 20($fp)				#i			
	blt		t0, zero, init_for_i_dos		#i >= 0

	lw		a0, 40($fp)		#words
	lw		a1, 20($fp)		#i
	lw		a2, 16($fp)		#heapSize
	
	jal		maxHeapify		#maxHeapify(words, i, heapSize)
	
	lw		t0, 20($fp)		#i
	subu	t0, t0, 1		#i-1
	sw		t0, 20($fp)		#i--
	
	b		for_i_uno

init_for_i_dos:
	#i = arraySize -1
	lw	t0, 20($fp)			# i
	lw	a1, 44($fp)			# arraysize
	
	subu	t0, a1, 1		# arraySize -1
	sw		t0, 20($fp)		# i = arraySize -1
	
	#for (i = arraySize -1; i >= 1; i--)
for_i_dos:

	lw		t0, 20($fp)		# i
	blt		t0, 1, fin		# i >= 1
	
swap:
	#swap(&words[0], &words[i]);
	lw		t0, 20($fp)		#i

	mul		t0, t0, 4		#[i]

	lw		a0, 40($fp)	#&words
	addu	t0, a0, t0	#&words[i]

	lw		t1, 40($fp)	#&words	

	lw		t2, 0(t0)	#words[i]
	lw		t3, 0(t1)	#words[0]

	sw		t2, 0(t1)	# words[0] = words[i];
	sw		t3, 0(t0)	# words[i] = words[i]

	#heapSize = heapSize -1
	lw		t0, 16($fp)
	subu	t0, t0, 1
	sw		t0, 16($fp)

	lw		a0, 40($fp)		#words
	move	a1, zero		#0
	lw		a2, 16($fp)		#heapSize
	
	jal		maxHeapify		#maxHeapify(words, 0, heapSize)
	
	
	lw		t0, 20($fp)		#i
	subu	t0, t0, 1		#i-1
	sw		t0, 20($fp)		#i--
	
	b		for_i_dos

fin:

# Destruccion del stack frame
	move	sp, $fp
	lw		ra,  32(sp)
	lw		$fp, 28(sp)

	addiu	sp, sp, 40
	jr		ra


	.end	heapSort
